<template>
  <div class="container-fluid text-white max-w-3xl">
    <h1 class="text-2xl font-bold mb-6">结算与支付</h1>

    <ol class="flex items-center gap-2 text-sm mb-8 text-white/70">
      <li :class="['px-3 py-1 rounded-full ring-1', step>=1 ? 'ring-emerald-400 text-white' : 'ring-white/15']">1. 填写收货信息</li>
      <li>→</li>
      <li :class="['px-3 py-1 rounded-full ring-1', step>=2 ? 'ring-emerald-400 text-white' : 'ring-white/15']">2. 选择支付方式</li>
      <li>→</li>
      <li :class="['px-3 py-1 rounded-full ring-1', step>=3 ? 'ring-emerald-400 text-white' : 'ring-white/15']">3. 支付</li>
    </ol>

    <!-- Step 1 收货信息 -->
    <section v-if="step===1" class="card-minimal p-6 space-y-4">
      <!-- 从已保存地址选择 -->
      <div v-if="savedAddresses.length" class="rounded-lg bg-white/5 ring-1 ring-white/10 p-4">
        <div class="text-white/70 text-sm mb-2">从已保存地址选择</div>
        <ul class="space-y-2">
          <li v-for="a in savedAddresses" :key="a.id" class="flex items-center justify-between">
            <div>
              <div class="font-medium">{{ a.name }} <span class="text-white/50 text-sm ml-2">{{ a.phone }}</span></div>
              <div class="text-white/60 text-sm">{{ a.address }}</div>
            </div>
            <button class="btn-outline" @click="useAddress(a)">选择</button>
          </li>
        </ul>
      </div>
      <div class="grid md:grid-cols-2 gap-4">
        <div>
          <label class="text-sm text-white/60">收货人</label>
          <input v-model.trim="form.name" class="input-control mt-1" placeholder="请输入姓名" />
        </div>
        <div>
          <label class="text-sm text-white/60">手机</label>
          <input v-model.trim="form.phone" class="input-control mt-1" placeholder="11位手机号" maxlength="11" inputmode="numeric" @input="digitsOnly('phone')" />
        </div>
        <div class="md:col-span-2">
          <label class="text-sm text-white/60">详细地址</label>
          <input v-model.trim="form.address" class="input-control mt-1" placeholder="街道、门牌等" />
        </div>
      </div>
      <div class="flex items-center justify-between pt-2">
        <span class="text-white/60 text-sm">信息仅用于配送，不会泄露给第三方</span>
        <button class="btn-primary" @click="goStep(2)">下一步</button>
      </div>
    </section>

    <!-- Step 2 支付方式 -->
    <section v-else-if="step===2" class="space-y-4">
      <div class="card-minimal p-4 text-left ring-1 ring-emerald-400">
        <div class="font-semibold">支付宝</div>
        <div class="text-xs text-white/50 mt-1">安全便捷的支付方式</div>
        <div class="text-emerald-400 text-xs mt-2">智能推荐</div>
      </div>
      <div class="flex items-center justify-between">
        <button class="btn-outline" @click="goStep(1)">上一步</button>
        <button class="btn-primary" @click="goStep(3)">立即支付</button>
      </div>
    </section>

    <!-- Step 3 支付进行中 + 结果 -->
    <section v-else-if="step===3" class="card-minimal p-6 space-y-4">
      <div class="flex items-center gap-3">
        <div class="w-5 h-5 border-2 border-emerald-400/40 border-t-emerald-400 rounded-full animate-spin"></div>
        <div class="text-white/80">支付跳转中…</div>
      </div>
      <div class="flex items-center justify-between">
        <div class="text-white/60 text-sm">订单号：{{ orderId }}</div>
        <button class="btn-outline" @click="restart">重新支付</button>
      </div>
      <div v-if="result==='success'" class="p-3 rounded-lg bg-emerald-500/10 text-emerald-300">支付成功，感谢您的购买！</div>
      <div v-else-if="result==='fail'" class="p-3 rounded-lg bg-red-500/10 text-red-300">支付失败，请重试或更换方式。</div>
    </section>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import toast from '../composables/toast'
import { useAuthStore } from '../stores/auth'
import { findUserAddress, addUserAddress } from '@/api/UserAddressApi.js'
// 移除下单 API，checkout 页面不再创建订单
import {AliPayAliPay} from '@/api/qiantaipaymentApi.js'
import { createOrder, searchOrders } from '@/api/orderApi.js'

// 简单延迟函数：等待后端生成订单号
function sleep(ms){ return new Promise(res => setTimeout(res, ms)) }

// 计算购物车签名：按 productId + buyNum 做稳定字符串，用于判断购物车是否已变化
function computeCartSignature(items){
  try{
    const norm = (items || []).map(i => ({ productId: i.productId, buyNum: i.buyNum }))
    norm.sort((a,b)=> String(a.productId).localeCompare(String(b.productId)) || (a.buyNum-b.buyNum))
    return JSON.stringify(norm)
  }catch(_){ return '' }
}

// 清理陈旧/无效的订单号：不同用户、非未支付状态的订单都清理
async function cleanupStaleOrder(){
  const existing = sessionStorage.getItem('currentOrderId')
  if(!existing) return
  const uid = sessionStorage.getItem('currentOrderUserId')
  if(String(uid || '') !== String(auth.user?.id || '')){
    sessionStorage.removeItem('currentOrderId')
    sessionStorage.removeItem('currentOrderCartHash')
    sessionStorage.removeItem('currentOrderUserId')
    orderId.value = ''
    return
  }
  const st = await fetchOrderStatus(existing)
  if(st !== 'UNPAID'){
    sessionStorage.removeItem('currentOrderId')
    sessionStorage.removeItem('currentOrderCartHash')
    sessionStorage.removeItem('currentOrderUserId')
    orderId.value = ''
  }
}

// Pinia 实例与派生数据
const auth = useAuthStore()
const savedAddresses = computed(() => auth.addresses || [])
const step = ref(1)

// 响应式数据
const result = ref('')
const orderId = ref('')
const selectedAddressId = ref(null)

// 表单
const form = ref({ name: '', phone: '', address: '' })

// 地址加载与选择填充
async function loadAddressesInCheckout(){
  if(!auth.user?.id) return
  if(!Array.isArray(auth.addresses) || auth.addresses.length===0){
    try{
      const resp = await findUserAddress(auth.user.id)
      const { code, data, msg } = resp?.data || {}
      if(code !== 200){ toast.error(msg || '获取地址失败'); return }
      auth.addresses = (data || []).map(it => ({
        id: it.id,
        name: it.reciver,
        phone: it.tel,
        address: it.detailAddress,
        _raw: it
      }))
    }catch(e){ toast.error(e.message || '获取地址失败') }
  }
}

function useAddress(a){
  form.value = { name: a.name || '', phone: a.phone || '', address: a.address || '' }
  selectedAddressId.value = a.id
  toast.success('已填充收货信息')
}

// 步骤切换
async function goStep(n){
  if(n===2){
    if(!form.value.name || !/^\d{11}$/.test(form.value.phone) || !form.value.address){
      toast.error('请正确填写收货信息（手机号需为11位数字）')
      return
    }
    // 若未选择已有地址，且已登录：后台异步保存为新地址（不阻塞页面流转）
    if(!selectedAddressId.value && auth.user?.id){
      const payload = {
        userId: auth.user.id,
        reciver: form.value.name,
        tel: form.value.phone,
        detailAddress: form.value.address
      }
      addUserAddress(payload)
        .then(async ()=>{
          await loadAddressesInCheckout()
          const hit = (auth.addresses||[]).find(a => a.name===form.value.name && a.phone===form.value.phone && a.address===form.value.address)
          if(hit) selectedAddressId.value = hit.id
        })
        .catch(()=>{/* 保存失败不影响继续操作 */})
    }
  }
  if(n===3){
    try{
      // 不在此处创建订单，仅复用已有订单号；若没有，做一次兜底创建
      if(!orderId.value){
        const ok = await ensureOrderInitialized()
        if(!ok) return
      }
      await payWithAlipay()
    }catch(e){ return }
  }
  step.value = n
}

// 进入页面时加载地址
onMounted(async () => {
  await loadAddressesInCheckout()
  await cleanupStaleOrder()
  const existing = sessionStorage.getItem('currentOrderId')
  if(existing) orderId.value = existing
})

// 仅校验/读取订单号：checkout 不负责创建订单
async function ensureOrderInitialized(){
  try{
    // 读取购物车并生成 items 与签名
    const cart = JSON.parse(localStorage.getItem('cart') || '[]')
    const items = (Array.isArray(cart) ? cart : [])
      .filter(i => (Number(i.qty) || 0) > 0)
      .map(i => {
        const pid = i.productId || i.id
        const num = Number(pid)
        return { productId: Number.isFinite(num) && !isNaN(num) ? num : String(pid), buyNum: Number(i.qty)||1 }
      })
    if(items.length === 0){ toast.error('购物车为空'); return false }
    if(!auth.user?.id){ toast.error('请先登录'); return false }
    const signature = computeCartSignature(items)

    // 先尝试复用既有订单号，但必须保证“用户一致 + 购物车一致”
    const existing = orderId.value || sessionStorage.getItem('currentOrderId')
    const storedSig = sessionStorage.getItem('currentOrderCartHash')
    const storedUid = sessionStorage.getItem('currentOrderUserId')
    if(existing && String(storedUid||'') === String(auth.user.id) && storedSig === signature){
      orderId.value = existing
      return true
    }else{
      // 不一致则清理旧缓存，进入创建新订单流程
      sessionStorage.removeItem('currentOrderId')
      sessionStorage.removeItem('currentOrderCartHash')
      sessionStorage.removeItem('currentOrderUserId')
    }

    // 确保 addressId 可用：若未选择但表单已填写，先创建地址并刷新
    let addrId = selectedAddressId.value
    const nameOk = !!form.value.name
    const phoneOk = /^\d{11}$/.test(form.value.phone || '')
    const addrOk = !!form.value.address
    if(!addrId && nameOk && phoneOk && addrOk){
      try{
        await addUserAddress({ customerId: auth.user.id, reciver: form.value.name, phone: form.value.phone, tel: form.value.phone, detailAddress: form.value.address })
        await loadAddressesInCheckout()
        const hit = (auth.addresses||[]).find(a =>
          a.name===form.value.name && (a.phone===form.value.phone) &&
          (a._raw?.detailAddress===form.value.address || (a.address||'').includes(form.value.address))
        )
        if(hit) addrId = hit.id
      }catch(_){ /* 地址创建失败不阻塞，可能后端下单允许不传 addressId */ }
    }

    // 创建订单
    const payload = { customerId: auth.user.id, addressId: addrId || undefined, orderItems: items, paymentMethod: 'alipay' }
    const resp = await createOrder(payload)
    const { code, data, msg } = resp?.data || {}
    const okCode = code === 200 || code === 0 || code === 6666
    if(!okCode){ throw new Error(msg || '下单失败') }

    // 订单号
    let oid = data?.orderNo || data?.orderId || data?.order_id || (typeof data==='object' ? data?.id : null)
    if(!oid){
      await sleep(3000)
      try{
        const q = await searchOrders({ customerId: auth.user.id, pageNum: 1, pageSize: 1 })
        const page = q?.data?.data
        const first = page?.list?.[0] || page?.records?.[0] || page?.data?.[0]
        oid = first?.orderNo || first?.orderId || first?.order_id || first?.id
      }catch(_){ /* 查询失败则继续走后续校验 */ }
    }

    if(!oid){ throw new Error('未获取到订单号') }
    orderId.value = String(oid)
    // 绑定 用户 + 购物车签名
    sessionStorage.setItem('currentOrderId', orderId.value)
    sessionStorage.setItem('currentOrderCartHash', signature)
    sessionStorage.setItem('currentOrderUserId', String(auth.user.id))
    // 清空购物车
    localStorage.setItem('cart', '[]')
    window.dispatchEvent(new CustomEvent('cart-updated'))
    return true
  }catch(e){ toast.error(e.message || '下单失败'); return false }
}

// 支付宝支付
async function payWithAlipay(){
  if(!orderId.value){ toast.error('订单号不存在'); return }
  try{
    const resp = await AliPayAliPay({ orderId: orderId.value })
    const html = resp?.data
    if(typeof html === 'string' && /<form|<!DOCTYPE|<html/i.test(html)){
      const blob = new Blob([html], { type: 'text/html' })
      const url = URL.createObjectURL(blob)
      window.open(url, '_self')
    }else{
      toast.error('支付网关返回异常')
    }
  }catch(e){ toast.error(e.message || '支付请求失败') }
}

// 重新开始支付流程
function restart(){
  step.value = 1
  result.value = ''
  orderId.value = ''
  sessionStorage.removeItem('currentOrderId')
  sessionStorage.removeItem('currentOrderCartHash')
  sessionStorage.removeItem('currentOrderUserId')
}

// 限制手机号只能为数字且最多11位
function digitsOnly(field) {
  if (field === 'phone') {
    form.value.phone = (form.value.phone || '').replace(/\D+/g, '').slice(0, 11)
  }
}

function normalizeStatus(s){
  if(s === undefined || s === null) return 'UNKNOWN'
  const v = String(s).toLowerCase()
  if(v.includes('已支付') || v.includes('success') || v.includes('paid') || v === '1' || v.includes('completed')) return 'PAID'
  if(v.includes('未支付') || v.includes('待支付') || v.includes('unpaid') || v.includes('pending') || v === '0') return 'UNPAID'
  if(v.includes('取消') || v.includes('cancel') || v.includes('closed') || v.includes('关闭')) return 'CANCELLED'
  return 'UNKNOWN'
}
</script>